package tech.aistar.corejava.day04;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ArraryCopyDemo {
    public static void main(String[] args) {
        //定义原数组
        int[] src = new int[] {1,2,3,4,5,6,7,8,9,10};
        //目标数组的初始容量
        int[] dest= new int[src.length];

        arraycopy(src,2,dest,0,4);

        System.out.println(Arrays.toString(dest));

    }

    public static void arraycopy(Object src,  int  srcPos, Object dest, int destPos, int length)

    {

        if (src == null || dest == null) {

            throw new NullPointerException("源和目的数组不能为空");
        }
        if (!src.getClass().isArray()|| !dest.getClass().isArray() ) {

            throw  new ArrayStoreException("源和目标必须是数组");

        }

        if (srcPos < 0 ||destPos < 0 || length <0|| srcPos+length > Array.getLength(src)
                || destPos +length > Array.getLength(dest)) {

            throw  new IndexOutOfBoundsException("索引越界");
        }
        if (src.getClass().getComponentType() !=
                dest.getClass().getComponentType()) {
            throw new ArrayStoreException("源和目标元素类型要一致");
        }
        for (int index = srcPos; index <srcPos +length ; index++) {
            //获取需要拷贝的原数组
            Object value = Array.get(src, index);
            //给目标数组添加元素
            Array.set(dest,destPos,value);
            destPos++;
        }
    }
}